package org.samples.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.samples.model.PagerModel;
import org.samples.model.ExamSubject;
import org.samples.model.ExamUser;
import org.samples.model.vo.CommonMessageResultVO;
import org.samples.model.vo.ExamScoreVO;
import org.samples.model.vo.ExamTestTypeVO;
import org.samples.model.vo.ExamTestVO;
import org.samples.model.vo.ExamUserVO;
import org.samples.model.vo.ExamSubjectVO;
import org.samples.service.ITeacherService;
import org.samples.util.ExcelUtils;
import org.samples.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

	/*@Autowired
	private LocaleResolver localeResolver;*/
	
	@Autowired
	private ITeacherService teacherService;
	
	@RequestMapping("")
	public String toTeacher(Model model){
		PagerModel<ExamUserVO> pageList = teacherService.findUserPage();
		model.addAttribute("pageList", pageList);
		return "teacher/manageStudent";
	}
	
	@RequestMapping(value = "/toManageTest")
	public String toManageTest(Model model){
		PagerModel<ExamTestVO> pageList = teacherService.findAllExamTest();
		model.addAttribute("pageList", pageList);
		return "teacher/manageTest";
	}
	
	@RequestMapping("/toManageSubject")
	public String toManageSubject(Model model){
		PagerModel<ExamSubject> pageList = teacherService.findSubjectPage();
		model.addAttribute("pageList", pageList);
		return "teacher/manageSubject";
	}
	
	@RequestMapping("/toManageStudent")
	public String toManageStudent(Model model){
		PagerModel<ExamUserVO> pageList = teacherService.findUserPage();
		model.addAttribute("pageList", pageList);
		return "teacher/manageStudent";
	}
	
	@RequestMapping("/toManageScore")
	public String toManageScore(Model model, @RequestParam(required=false)Map<String, String> conditionMap){
		PagerModel<ExamScoreVO> pageList = teacherService.getAllScore(conditionMap);
		model.addAttribute("pageList", pageList);
		return "teacher/manageScore";
	}
	
	/*@RequestMapping(value = "/changeLocaleSub")
	public String changeLocale(HttpServletRequest requese, HttpServletResponse response, String localType){
		if("en_US".equals(localType)){
			localeResolver.setLocale(requese, response, Locale.US);
		} else if("zh_CN".equals(localType)){
			localeResolver.setLocale(requese, response, Locale.CHINA);
		}
		return "redirect:/subject";
	}*/
	
	//-------------------------------------------I am the dividing line-------------------------------------------
	//test
	
	@ResponseBody
	@RequestMapping(value = "/getSubjectAndTypes", method = RequestMethod.POST)
	public Map<String, Object> getSubjectAndTypes() throws Exception{
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<ExamSubjectVO> subjectList = teacherService.getSubjectList();
		List<ExamTestTypeVO> testTypeList = teacherService.getTestTypeList();
		resultMap.put("subjectList", subjectList);
		resultMap.put("testTypeList", testTypeList);
		return resultMap;
	}
	
	@RequestMapping(value = "/saveTest", method = RequestMethod.POST)
	public String saveTest(RedirectAttributes redirectAttributes, ExamTestVO examTestVO){
		try{
			teacherService.createExamTest(examTestVO);;
			redirectAttributes.addFlashAttribute("message", "添加成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "添加失败");
		}
		return "redirect:/teacher/toManageTest";
	}
	
	/*@ResponseBody
	@RequestMapping(value = "/updateTest", method = RequestMethod.POST)
	public CommonMessageResultVO updateTest(@Valid ExamTestVO examTestVO, BindingResult bindingResult){
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
		if(bindingResult.hasErrors()){
			List<ObjectError> errorList = bindingResult.getAllErrors();
			for(ObjectError error : errorList){
				FieldError fe = (FieldError) error;
				messageMap.put(fe.getField(), fe.getDefaultMessage());
			}
			resultVO.setMessageMap(messageMap);
			return resultVO;
		}
		try{
			teacherService.editExamTest(examTestVO);
			resultVO.setSuccess(true);
		} catch (Exception e){
			e.printStackTrace();
			messageMap.put("message", e.getMessage());
			resultVO.setMessageMap(messageMap);
		}
		return resultVO;
	}*/
	
	@RequestMapping(value = "/updateTest", method = RequestMethod.POST)
	public String updateTest(RedirectAttributes redirectAttributes, ExamTestVO examTestVO){
		try{
			teacherService.editExamTest(examTestVO);
			redirectAttributes.addFlashAttribute("message", "修改成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "修改失败");
		}
		return "redirect:/teacher/toManageTest";
	}
	
	@RequestMapping(value = "/deleteTest/{id}", method = RequestMethod.GET)
	public String deleteTest(RedirectAttributes redirectAttributes, @PathVariable Integer id){
		try{
			teacherService.deleteExamTest(id);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "删除失败");
		}
		return "redirect:/teacher/toManageTest";
	}
	
	@ResponseBody
	@RequestMapping(value = "/getTestById", method = RequestMethod.POST)
	public ExamTestVO getTestById(Integer testId){
		ExamTestVO resultVO = teacherService.getExamTestById(testId);
		return resultVO;
	}
	
	//test
	//-------------------------------------------I am the dividing line-------------------------------------------
	//subject
	
	@RequestMapping(value = "/saveSubject", method = RequestMethod.POST)
	public String saveSubject(RedirectAttributes redirectAttributes, ExamSubject subject){
		try{
			teacherService.creatSubject(subject);
			redirectAttributes.addFlashAttribute("message", "添加成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "添加失败");
		}
		return "redirect:/teacher/toManageSubject";
	}
	
	@RequestMapping(value = "/updateSubject", method = RequestMethod.POST)
	public String updateSubject(RedirectAttributes redirectAttributes, ExamSubject subject){
		try{
			teacherService.editSubject(subject);;
			redirectAttributes.addFlashAttribute("message", "修改成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "修改失败");
		}
		return "redirect:/teacher/toManageSubject";
	}
	
	@RequestMapping(value = "/deleteSubject/{id}", method = RequestMethod.GET)
	public String deleteSubject(RedirectAttributes redirectAttributes, @PathVariable Integer id){
		if(teacherService.getAllUserBySubject(id).size() > 0){
			redirectAttributes.addFlashAttribute("message", "删除失败，该科目有学生参考或准备参考");
			return "redirect:/teacher/toManageSubject";
		}
		try{
			teacherService.deleteSubject(id);
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "删除失败");
		}
		return "redirect:/teacher/toManageSubject";
	}
	
	@ResponseBody
	@RequestMapping(value = "/getAllStudent")
	public Map<String, Object> getAllStudent(Integer subId){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("allUser", teacherService.findUserPage().getDates());
		resultMap.put("selectedUser", teacherService.getAllUserBySubject(subId));
		return resultMap;
	}
	
	@ResponseBody
	@RequestMapping(value = "/saveSubjectStudent" )
	public Map<String, Object> saveSubjectStudent(@RequestParam(name = "subjectStudents[]", required=false)String[] subjectStudents , Integer subId ){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", false);
		List<String> list = new ArrayList<String>();
		if(subjectStudents != null)
		for(String student : subjectStudents){
			list.add(student);
		}
		try {
			teacherService.saveSubjectStudent(list, subId);
			resultMap.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultMap;
	}
	
	//subject
	//-------------------------------------------I am the dividing line-------------------------------------------
	//student
	
	@RequestMapping(value = "/saveStudent", method = RequestMethod.POST)
	public String saveStudent(RedirectAttributes redirectAttributes, ExamUser user){
		if(teacherService.getByUserName(user.getUserName()) != null){
			redirectAttributes.addFlashAttribute("message", "用户名已存在");
			return "redirect:/teacher/toManageStudent";
		} else if(teacherService.getUserById(user.getUserId()) != null){
			redirectAttributes.addFlashAttribute("message", "id已存在");
			return "redirect:/teacher/toManageStudent";
		}
		user.setPassword(MD5Utils.getMD5Code("123456"));
		try{
			teacherService.creatUser(user);
			redirectAttributes.addFlashAttribute("message", "添加成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "添加失败");
		}
		return "redirect:/teacher/toManageStudent";
	}
	
	@RequestMapping(value = "/updateStudent", method = RequestMethod.POST)
	public String updateStudent(RedirectAttributes redirectAttributes, ExamUser user){
		user.setPassword(MD5Utils.getMD5Code("123456"));
		try{
			teacherService.editUser(user);
			redirectAttributes.addFlashAttribute("message", "修改成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "修改失败");
		}
		return "redirect:/teacher/toManageStudent";
	}
	
	@RequestMapping(value = "/deleteStudent/{userId}", method = RequestMethod.GET)
	public String deleteStudent(RedirectAttributes redirectAttributes, @PathVariable String userId){
		try{
			teacherService.deleteUser(userId);;
			redirectAttributes.addFlashAttribute("message", "删除成功");
		} catch (Exception e){
			e.printStackTrace();
			redirectAttributes.addFlashAttribute("message", "删除失败");
		}
		return "redirect:/teacher/toManageStudent";
	}
	
	@ResponseBody
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public CommonMessageResultVO upload(@RequestParam(value = "uploadFile") MultipartFile[] uploadFile, HttpSession session, ModelMap model) {
		CommonMessageResultVO resultVO = new CommonMessageResultVO();
		MultipartFile uploadSimpleFile = uploadFile[0];
		String fileName = uploadSimpleFile.getOriginalFilename();
		String postfix = fileName.substring(fileName.lastIndexOf("."));
		Map<String, String> messageMap = new HashMap<String, String>();
		resultVO.setSuccess(false);
			try {
				if(ExcelUtils.OFFICE_EXCEL_2003_POSTFIX.equals(postfix) || ExcelUtils.OFFICE_EXCEL_2007_POSTFIX.equals(postfix)){
					teacherService.saveUserByExcel(uploadSimpleFile.getInputStream(), postfix);
					resultVO.setSuccess(true);
				}else{
					messageMap.put("message", "文件格式不正确");
					resultVO.setMessageMap(messageMap);
				}
			} catch (IOException e) {
				e.printStackTrace();
				messageMap.put("message", "批量导入失败");
				resultVO.setMessageMap(messageMap);
			}
		return resultVO;
	}
	
	//student
	//-------------------------------------------I am the dividing line-------------------------------------------
	//score
	
	@ResponseBody
	@RequestMapping(value = "/queryScore", method = RequestMethod.POST)
	public PagerModel<ExamScoreVO> queryScore(@RequestParam(required=false)Map<String, String> conditionMap) throws Exception{
		PagerModel<ExamScoreVO> scoreVO = teacherService.getAllScore(conditionMap);
		return scoreVO;
	}
	
}
